package com.example.mybatis.service.impl;

import com.example.mybatis.mapper.AccountMapper;
import com.example.mybatis.pojo.Account;
import com.example.mybatis.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName:AccountServiceImpl
 * Package:com.example.mybatis.service.impl
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/5/12-9:10
 * @Version:v1.0
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;


    @Override
    public int save(Account act) {
        return accountMapper.insert(act);
    }

    @Override
    public int deleteByActno(String actno) {
        return accountMapper.deleteByActno(actno);
    }

    @Override
    public int modify(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public Account getByActno(String actno) {
        return accountMapper.selectByActno(actno);
    }

    @Override
    public List<Account> getAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromActno, String toActno, double moeny) {
        Account formAct = accountMapper.selectByActno(fromActno);
        if (formAct.getBalance() < moeny) {
            throw new RuntimeException("余额不足");

        }
        Account toAct = accountMapper.selectByActno(toActno);
        formAct.setBalance(formAct.getBalance() - moeny);
        toAct.setBalance(toAct.getBalance() + moeny);
        int count = accountMapper.update(formAct);

//        String s =null;
//        s.toString();
        count += accountMapper.update(toAct);

        if (count!=2){
            throw new RuntimeException("转账失败");
        }
    }
}
